package com.automation.ljf.strategy.impl;

import com.automation.ljf.domain.dataobject.CaseStepDO;
import com.automation.ljf.strategy.OperationStrategy;
import com.automation.ljf.util.DriverUtils;
import com.automation.ljf.util.ResultMessage;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.springframework.stereotype.Component;

/**
 * 双击操作
 *
 * @author lijiefeng
 * @since 2021/8/25
 */
@Component("DOUBLE_CLICK")
@Slf4j
public class DoubleClickStrategyImpl implements OperationStrategy {
    @Override
    public ResultMessage doOperation(ChromeDriver driver, CaseStepDO caseStepDO, String jsonData) {

        String windowHandle = driver.getWindowHandle();
        if (!DriverUtils.isElementExist(driver, By.xpath(caseStepDO.getStepXpath()))){
            return ResultMessage.error("测试用例" + caseStepDO.getCaseId() + "的步骤" + caseStepDO.getStepId() + "出现异常")
                    .addData("errorMsg", "元素不存在，无法定位").addData("window", windowHandle);
        }
        try{
            WebElement we = driver.findElement(By.xpath(caseStepDO.getStepXpath()));
            if (!we.isEnabled()){
                return ResultMessage.error("测试用例" + caseStepDO.getCaseId() + "的步骤" + caseStepDO.getStepId() + "出现异常")
                        .addData("errorMsg", "元素不可操作/编辑").addData("window", windowHandle);
            }
            Actions actions = new Actions(driver);
            actions.doubleClick(we).perform();
            Thread.sleep(1000);
        }catch (Exception e){
            return ResultMessage.error("测试用例" + caseStepDO.getCaseId() + "的步骤" + caseStepDO.getStepId() + "出现异常")
                    .addData("errorMsg", "不可预知的错误").addData("window", windowHandle);
        }
        return ResultMessage.ok("操作成功").addData("window", windowHandle);
    }
}
